<template>
  <div class="main">
    <!-- 头部区域 Start -->
    <div class="head">
      <!-- 头部按钮区域 Start -->
      <div class="btn">
        <div class="rule btn-size" @click="dialogShow('rule')"></div>
        <div ref="box" class="box">
          <div v-show="!awardRankShow" class="record btn-size" @click="dialogShow('record')"></div>
          <div v-show="!awardRankShow" class="award btn-size" @click="dialogShow('award')"></div>
          <div v-show="awardRankShow" class="award-rank btn-size" @click="dialogShow('awardRank')"></div>
        </div>
      </div>
      <!-- 头部按钮区域 End -->
    </div>
    <!-- 头部区域 End -->

    <!-- tab栏按钮 Start -->
    <div class="tab-btn">
      <div ref="puzzle" class="puzzle puzzleOn" @click="tabsChange('puzzle')"></div>
      <div ref="rank" class="rank rankOff" @click="tabsChange('rank')"></div>
    </div>
    <!-- tab栏按钮 End -->

    <!-- 主体区域 Start -->
    <div class="content">
      <!-- 拼图主体 Start -->
      <div v-show="!rankShow" class="puzzle-content">
        <!-- 拼图区域 Start -->
        <div class="puzzle-main">
          <!-- 拼图头部区域 Start -->
          <div class="puzzle-head">
            <div class="icon">
              <img class="puzzle-pic" src="@/assets/childrenDay/puzzle-icon.png" alt="" />
              <span class="puzzle-num">{{ data.current_puzzle?.magic_pieces_num }}</span>
            </div>
            <p class="explain">使用拼图碎片将拼图拼好可获得奖励</p>
          </div>
          <!-- 拼图头部区域 End -->

          <!-- 拼图 Start -->
          <div ref="puzzleBody" class="puzzle-body">
            <SmallDebris v-if="data.current_puzzle?.last_puzzle_no < 4" :data="data" />
            <Mid v-if="data.current_puzzle?.last_puzzle_no === 4" :data="data" />
            <BigDebris v-if="data.current_puzzle?.last_puzzle_no === 5" :data="data" />
          </div>
          <div class="progress">
            <p class="progress-num">{{ `拼图进度${data.current_puzzle && data.current_puzzle.progress}%` }}</p>
            <van-slider
              v-model="data.current_puzzle.progress"
              bar-height="20px"
              inactive-color="#278EFD"
              active-color="#00aff9"
            >
              <template #button> </template>
            </van-slider>
          </div>
          <!-- 拼图 End -->

          <!-- 按钮区域 Start -->
          <div class="bottom-btn">
            <div class="use use-btn" @click="useDebris"></div>
            <div class="use-max use-btn" @click="useAllDebris"></div>
          </div>
          <!-- 按钮区域 End -->
        </div>
        <!-- 拼图区域 End -->

        <!-- 拼图广场 Start -->
        <div class="piazza">
          <div class="title"></div>
          <p class="piazza-hint">拼图拼好后将自动跳转下一个拼图，每种拼图可获得的奖励不同。</p>
          <!-- 轮播区域 -->
          <van-swipe :loop="false" :width="87" :initial-swipe="data.current_puzzle.last_puzzle_no">
            <van-swipe-item>
              <div class="pic">
                <van-image width="74" height="69" :src="imgBg.castle" @click="preview(1)" />
                <div class="name">魔法城堡</div>
              </div>
              <div class="right"></div>
            </van-swipe-item>
            <van-swipe-item>
              <div class="pic">
                <van-image width="74" height="69" :src="imgBg.horse" @click="preview(2)" />
                <div class="name">旋转木马</div>
              </div>
              <div class="right"></div>
            </van-swipe-item>
            <van-swipe-item>
              <div class="pic">
                <van-image width="74" height="69" :src="imgBg.house" @click="preview(3)" />
                <div class="name">飞屋妙想</div>
              </div>

              <div class="right"></div>
            </van-swipe-item>
            <van-swipe-item>
              <div class="pic">
                <van-image width="74" height="69" :src="imgBg.twelve" @click="preview(4)" />
                <div class="name">童心派对</div>
              </div>
              <div class="right"></div>
            </van-swipe-item>
            <van-swipe-item class="last">
              <div class="pic">
                <van-image width="74" height="69" :src="imgBg.sixteen" @click="preview(5)" />
                <div class="name">大童小忆</div>
              </div>
            </van-swipe-item>
            <template #indicator></template>
          </van-swipe>
        </div>
        <!-- 拼图广场 End -->
      </div>
      <!-- 拼图主体 End -->

      <!-- 榜单主体 Start -->
      <div v-show="rankShow" class="rank-content">
        <!-- 榜单区域 Start -->
        <div class="rank-main">
          <div class="rank-body">
            <!-- 排名榜单 -->
            <div v-for="(item, i) in rankList.list" :key="item.id" class="rank-list" @click="goUserIndex(item)">
              <div class="ranking">
                {{ item.rank > 3 ? item.rank : '' }}
                <img
                  v-if="item.rank < 4"
                  class="rank-img"
                  :src="item.rank === 1 ? one : item.rank === 2 ? two : item.rank === 3 ? three : ''"
                  alt=""
                />
              </div>
              <div class="icon">
                <van-image round width="48px" height="48px" :src="item.user.avatar" />
              </div>
              <div class="info">
                <div class="name">{{ item.user.nickname }}</div>
                <div class="id">{{ `ID:${item.user.code}` }}</div>
              </div>
              <div class="count">
                <div class="text">{{ item.rank === 1 ? 'TOP1' : '距离上一名' }}</div>
                <div v-if="i !== 0" class="num">{{ `${filter(item.diff)}童趣值` }}</div>
              </div>
            </div>
            <van-empty v-if="rankList.length === 0" :image="nothing" description="暂无用户上榜" />
            <!-- 个人信息 -->
            <div class="user-info rank-list" @click="goUserIndex(rankList.user)">
              <div class="ranking">
                {{
                  rankList.user?.rank === 0
                    ? '未上榜'
                    : rankList.user?.rank === ''
                    ? '未上榜'
                    : rankList.user?.rank < 4
                    ? ''
                    : rankList.user?.rank
                }}
                <img
                  v-if="rankList.user?.rank < 4 && rankList.user?.rank > 0"
                  class="rank-img"
                  :src="
                    rankList.user?.rank === 1
                      ? one
                      : rankList.user?.rank === 2
                      ? two
                      : rankList.user?.rank === 3
                      ? three
                      : ''
                  "
                  alt=""
                />
              </div>
              <div class="icon">
                <van-image round width="48px" height="48px" :src="rankList.user?.user?.avatar" />
              </div>
              <div class="info">
                <div class="name">{{ rankList.user?.user?.nickname }}</div>
                <div class="id">{{ `ID:${rankList.user?.user?.code}` }}</div>
              </div>
              <div class="count">
                <div class="text">
                  {{
                    rankList.user?.rank === 0
                      ? '距离上榜'
                      : rankList.user?.rank === ''
                      ? '距离上榜'
                      : rankList.user?.rank === 1
                      ? 'TOP1'
                      : '距离上一名'
                  }}
                </div>
                <div v-if="rankList.user?.rank !== 1" class="num">
                  {{ `${filter(rankList.user?.diff)}童趣值` }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 榜单区域 End -->
      </div>
      <!-- 榜单主体 End -->
    </div>
    <!-- 主体区域 End -->

    <!-- 活动规则 -->
    <Rule :show="ruleShow" @close="close" />
    <!-- 获取记录 -->
    <Record :show="recordShow" @close="close" />
    <!-- 奖励预览 -->
    <Award :show="awardShow" @close="close" />
    <!-- 榜单奖励 -->
    <AwardRank :show="awardRankDialogShow" @close="close" />
    <!-- 使用魔法碎片确认弹窗 -->
    <UseDialog :show="useDialogShow" :text="text" @close="dialogClose" @send="sendDebris" />
    <!-- 获得奖励弹窗 -->
    <GetAward :show="getAwardShow" :list="giftList" @close="getAwardClose" />
    <!-- 重置弹窗 -->
    <Reset :show="resetShow" @close="resetClose" @send="resetSend" />
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ImagePreview, Toast } from 'vant'
import { getIndexInfoApi, getRankListApi, useMagicApi, resetGameApi } from '@/netWork/puzzleHome.js'
import { sendMessage } from '@/utils/index.js'
// 组件引入
import Rule from './components/rule/rule.vue'
import Record from './components/record/record.vue'
import Award from './components/award/award.vue'
import SmallDebris from './components/bright/small/small.vue'
import Mid from './components/bright/mid/mid.vue'
import BigDebris from './components/bright/big/big.vue'
import AwardRank from './components/awardRank/awardRank.vue'
import UseDialog from './components/useDialog/useDialog.vue'
import GetAward from './components/getAward/getAward.vue'
import Reset from './components/reset/reset.vue'
// 图片引入
import nothing from '@/assets/childrenDay/nothingG.png'
import castleOff from '@/assets/childrenDay/puzzle/castle/castleBg.png'
import castleOn from '@/assets/childrenDay/puzzle/castle/castleOn.png'
import horseOff from '@/assets/childrenDay/puzzle/horse/horseBg.png'
import horseOn from '@/assets/childrenDay/puzzle/horse/horseOn.png'
import houseOff from '@/assets/childrenDay/puzzle/house/houseBg.png'
import houseOn from '@/assets/childrenDay/puzzle/house/houseOn.png'
import twelveOff from '@/assets/childrenDay/puzzle/12/12Bg.png'
import twelveOn from '@/assets/childrenDay/puzzle/12/12On.png'
import sixteenOff from '@/assets/childrenDay/puzzle/16/16Bg.png'
import sixteenOn from '@/assets/childrenDay/puzzle/16/16On.png'
import one from '@/assets/childrenDay/1.png'
import two from '@/assets/childrenDay/2.png'
import three from '@/assets/childrenDay/3.png'
// 前往用户主页
const goUserIndex = (value) => {
  console.log(value.user.id, '前往用户主页')
  console.log(`"${JSON.stringify({ userId: `${value.user.id}` })}"`)
  sendMessage('onUserCenterBtnClick', { userId: value.user.id })
}
// 获取首页信息
const resetShow = ref(false)
const getIndexInfo = async (value) => {
  const res = await getIndexInfoApi()
  data.value = res.data
  if (res.data.prizes.length > 0) {
    giftList.value = res.data.prizes
    getAwardShow.value = true
  }
  plazaBgMatching()
  if (!value) {
    if (
      res.data.current_puzzle.is_finish === 1 &&
      res.data.current_puzzle.last_puzzle_no === 5 &&
      res.data.prizes.length === 0
    ) {
      resetShow.value = true
    }
  }
}
getIndexInfo()
// 获取榜单信息
const getRankList = async () => {
  const res = await getRankListApi()
  rankList.value = res.data
}
// 确认重置
const resetSend = async () => {
  await resetGameApi()
  resetClose()
  getIndexInfo()
}
// 重置弹窗关闭
const resetClose = () => {
  resetShow.value = false
}
// 弹窗显示
const ruleShow = ref(false)
const recordShow = ref(false)
const awardShow = ref(false)
const awardRankDialogShow = ref(false)
const dialogShow = (value) => {
  switch (value) {
    case 'rule':
      ruleShow.value = true
      break
    case 'record':
      recordShow.value = true
      break
    case 'award':
      awardShow.value = true
      break
    case 'awardRank':
      awardRankDialogShow.value = true
  }
}
// 首页头部四个弹窗关闭
const close = (value) => {
  switch (value) {
    case 'rule':
      ruleShow.value = false
      break
    case 'record':
      recordShow.value = false
      break
    case 'award':
      awardShow.value = false
      break
    case 'awardRank':
      awardRankDialogShow.value = false
  }
  getIndexInfo('1')
}
// tab栏按钮切换
const box = ref(null)
const rankShow = ref(false)
const puzzle = ref()
const rank = ref()
const awardRankShow = ref(false)
const tabsChange = (value) => {
  if (value === 'puzzle') {
    box.value.style.justifyContent = 'space-between'
    awardRankShow.value = false
    rank.value.classList.remove('rankOn')
    rank.value.classList.add('rankOff')
    puzzle.value.classList.add('puzzleOn')
    puzzle.value.classList.remove('puzzleOff')
    rankShow.value = false
    getIndexInfo('1')
  } else {
    box.value.style.justifyContent = 'flex-end'
    awardRankShow.value = true
    puzzle.value.classList.remove('puzzleOn')
    puzzle.value.classList.add('puzzleOff')
    puzzle.value.classList.remove('rankOff')
    rank.value.classList.add('rankOn')
    rankShow.value = true
    getRankList('1')
  }
}
// 首頁信息
const data = ref({
  current_puzzle: {
    progress: 0,
  },
})

// 拼图广场图片
const imgBg = ref({
  castle: castleOff,
  horse: horseOff,
  house: houseOff,
  twelve: twelveOff,
  sixteen: sixteenOff,
})
// 拼图广场图片匹配
const plazaBgMatching = () => {
  if (data.value.current_puzzle?.last_puzzle_no === 2) {
    imgBg.value.castle = castleOn
  } else if (data.value.current_puzzle?.last_puzzle_no === 3) {
    imgBg.value.castle = castleOn
    imgBg.value.horse = horseOn
  } else if (data.value.current_puzzle?.last_puzzle_no === 4) {
    imgBg.value.castle = castleOn
    imgBg.value.horse = horseOn
    imgBg.value.house = houseOn
  } else if (data.value.current_puzzle?.last_puzzle_no === 5 && data.value.current_puzzle?.is_finish === 0) {
    imgBg.value.castle = castleOn
    imgBg.value.horse = horseOn
    imgBg.value.house = houseOn
    imgBg.value.twelve = twelveOn
  } else if (data.value.current_puzzle?.last_puzzle_no === 5 && data.value.current_puzzle?.is_finish === 1) {
    imgBg.value.castle = castleOn
    imgBg.value.horse = horseOn
    imgBg.value.house = houseOn
    imgBg.value.twelve = twelveOn
    imgBg.value.sixteen = sixteenOn
  } else {
    imgBg.value = {
      castle: castleOff,
      horse: horseOff,
      house: houseOff,
      twelve: twelveOff,
      sixteen: sixteenOff,
    }
  }
}

// 拼图区域图片匹配
const puzzleBody = ref(null)
onMounted(() => {
  watch(
    () => data.value.current_puzzle.last_puzzle_no,
    (value) => {
      switch (value) {
        case 1:
          puzzleBody.value.classList.add('castleBg')
          puzzleBody.value.classList.remove('horseBg')
          puzzleBody.value.classList.remove('houseBg')
          puzzleBody.value.classList.remove('twelveBg')
          puzzleBody.value.classList.remove('sixteenBg')
          break
        case 2:
          puzzleBody.value.classList.add('horseBg')
          puzzleBody.value.classList.remove('castleBg')
          puzzleBody.value.classList.remove('houseBg')
          puzzleBody.value.classList.remove('twelveBg')
          puzzleBody.value.classList.remove('sixteenBg')
          break
        case 3:
          puzzleBody.value.classList.add('houseBg')
          puzzleBody.value.classList.remove('castleBg')
          puzzleBody.value.classList.remove('horseBg')
          puzzleBody.value.classList.remove('twelveBg')
          puzzleBody.value.classList.remove('sixteenBg')
          break
        case 4:
          puzzleBody.value.classList.add('twelveBg')
          puzzleBody.value.classList.remove('castleBg')
          puzzleBody.value.classList.remove('horseBg')
          puzzleBody.value.classList.remove('houseBg')
          puzzleBody.value.classList.remove('sixteenBg')
          break
        case 5:
          puzzleBody.value.classList.add('sixteenBg')
          puzzleBody.value.classList.remove('castleBg')
          puzzleBody.value.classList.remove('horseBg')
          puzzleBody.value.classList.remove('houseBg')
          puzzleBody.value.classList.remove('twelveBg')
      }
    },
    { immediate: true, deep: true }
  )
})
// 使用魔法碎片
const useDialogShow = ref(false)
const text = ref('')
const num = ref(0)
const giftList = ref([])
const useDebris = () => {
  if (data.value.current_puzzle.is_finish === 1) {
    resetShow.value = true
  } else {
    if (data.value.current_puzzle?.magic_pieces_num === 0) {
      return Toast('魔法碎片数量不足，请获取魔法碎片后再使用！')
    }
    num.value = 1
    text.value = '是否确认使用魔法碎片？'
    useDialogShow.value = true
  }
}
// 使用最大数量
const useAllDebris = () => {
  if (data.value.current_puzzle.is_finish === 1) {
    resetShow.value = true
  } else {
    if (data.value.current_puzzle?.magic_pieces_num === 0) {
      return Toast('魔法碎片数量不足，请获取魔法碎片后再使用！')
    }
    num.value = 2
    text.value = '是否确认使用所有魔法碎片？'
    useDialogShow.value = true
  }
}
// 使用碎片 发送请求
const getAwardShow = ref(false)
const sendDebris = async () => {
  try {
    const res = await useMagicApi({ type: num.value })
    giftList.value = res.data.prizes
    if (res.data.prizes.length > 0) {
      getAwardShow.value = true
    }
    dialogClose(1)
  } catch (error) {
    dialogClose()
    Toast.fail(error.message)
    setTimeout(() => {
      getIndexInfo()
    }, 500)
  }
}
// 魔法碎片弹窗关闭
const dialogClose = (value) => {
  useDialogShow.value = false
  if (value === 1) {
    getIndexInfo()
  }
}
// 获得奖励弹窗关闭
const getAwardClose = () => {
  getAwardShow.value = false
  getIndexInfo()
  if (data.value.current_puzzle.is_finish === 1) {
    resetShow.value = true
  }
}
// 图片预览
const preview = (value) => {
  const url = ref(null)
  switch (value) {
    case 1:
      url.value = castleOn
      break
    case 2:
      url.value = horseOn
      break
    case 3:
      url.value = houseOn
      break
    case 4:
      url.value = twelveOn
      break
    default:
      url.value = sixteenOn
  }
  ImagePreview([url.value])
}

// 榜单假数据
const rankList = ref([])
// 过万过滤保留一位小数
const filter = (value) => {
  return value > 9999 ? (Math.floor((value / 10000) * 100) / 100).toFixed(1) + 'w' : value
}
</script>
<style lang="scss" scoped>
@import './style.scss';
</style>
